//
//  HJShareSendMessageInputBar.m
//  KaiChat
//
//  Created by lx on 2024/3/8.
//

#import "HJShareSendMessageInputBar.h"
#import "NSString+emoji.h"
#import "TUIDefine.h"
#import "HJResponderTextView.h"
#import "TUIDefine.h"
#import "UIView+TUILayout.h"
#import "HJGradientButton.h"
#import "HJAlertController.h"
#import "NSString+QMUI.h"
#import <MBProgressHUD.h>
#import "HJShareCountView.h"

@interface HJShareSendMessageInputBar() <UITextViewDelegate>

@property (nonatomic, assign) BOOL isFocusOn;
@property (nonatomic, assign) NSInteger maximumTextLength;
@property (nonatomic, assign) long long lastTimestamp;
@property (nonatomic, weak) HJShareCountView *shareCountView;


@end

@implementation HJShareSendMessageInputBar


- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if(self){
        [self setupViews];
        [self defaultLayout];

    }
    return self;
}

- (void)setupViews
{
    
    self.maximumTextLength = 2048;
    
     _sendButton = [[UIButton alloc] init];
    [_sendButton addTarget:self action:@selector(clickSendBtn:) forControlEvents:UIControlEventTouchUpInside];
    [_sendButton setImage:[UIImage imageNamed:@"input_bar_send_select"] forState:UIControlStateNormal];
    _sendButton.backgroundColor = UIColor.whiteColor;
    [self addSubview:_sendButton];
    
    HJShareCountView *shareCountView = [HJShareCountView addToView:_sendButton];
    _shareCountView = shareCountView;
 
    _inputTextView = [[HJResponderTextView alloc] init];
    _inputTextView.delegate = self;
    _inputTextView.placeholder = @"Add description";
    CGFloat topMargin = (40 - ceilf(UIFontMake(14).lineHeight)) * 0.5;
    _inputTextView.textContainerInset = UIEdgeInsetsMake(topMargin, 10, 10, 10);
    [_inputTextView setFont:UIFontMake(14)];
    _inputTextView.tintColor = UIColor.tj_cursorColor;
    _inputTextView.backgroundColor = UIColor.tj_F6F6F6Color;
    _inputTextView.textColor = UIColor.tj_333333Color;
    [_inputTextView setReturnKeyType:UIReturnKeySend];
    _inputTextView.addCornerRadius(10);
        
    [self addSubview:_inputTextView];
}

- (void)defaultLayout {
    

    CGSize buttonSize = TTextView_Button_Size;
    
    CGFloat buttonOriginY = (40 - buttonSize.height) * 0.5;
    
    _sendButton.frame = CGRectMake(Screen_Width - buttonSize.width - 12, buttonOriginY, buttonSize.width, buttonSize.height);

    CGFloat beginX = leftRightMargin;
    CGFloat endX =  KScreenWidth - 2 - (KScreenWidth - _sendButton.tj_x);
    
    _inputTextView.frame = CGRectMake(beginX, 0, endX - beginX, 40);;
    
    [self.placeholderLabel sizeToFit];
}

- (void)setCount:(NSInteger)count {
    _count = count;
    
    [_shareCountView setNum:count];
    _shareCountView.frame = CGRectMake(8, -_shareCountView.bounds.size.height * 0.5 + 8, _shareCountView.bounds.size.width, _shareCountView.bounds.size.height);
}

- (void)layoutButton:(CGFloat)height
{
    CGRect frame = self.frame;
    CGFloat offset = height - frame.size.height;
    frame.size.height = height;
    self.frame = frame;
    
    CGSize buttonSize = TTextView_Button_Size;
    CGFloat bottomMargin = (40 - buttonSize.height) * 0.5;
    CGFloat originY = frame.size.height - buttonSize.height - bottomMargin - 10;
    
    CGRect sendButtonFrame = _sendButton.frame;
    sendButtonFrame.origin.y = originY;
    _sendButton.frame = sendButtonFrame;
    
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didChangeInputHeight:)]){
        [_delegate inputBar:self didChangeInputHeight:offset];
    }
}

- (void)clickSendBtn:(UIButton *)sender {
    [self sendTextWithTextView:self.inputTextView];
}


- (void)textViewDidBeginEditing:(UITextView *)textView {
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:textViewDidBeginEditing:)]){
        [_delegate inputBar:self textViewDidBeginEditing:textView.text];
    }
}

- (void)textViewDidChange:(UITextView *)textView
{
 
    if (textView.text.length) {
        self.inputTextView.placeholderLabel.alpha = 0;
    } else {
        self.inputTextView.placeholderLabel.alpha = 1;
    }
    
    CGSize size = [_inputTextView sizeThatFits:CGSizeMake(_inputTextView.frame.size.width, TTextView_TextView_Height_Max)];
    CGFloat oldHeight = _inputTextView.frame.size.height;
    CGFloat newHeight = size.height;
    
    if(newHeight > TTextView_TextView_Height_Max){
        newHeight = TTextView_TextView_Height_Max;
    }
    if(newHeight < 40){
        newHeight = 40;
    }
    if(oldHeight == newHeight){
        return;
    }
    
    __weak typeof(self) ws = self;
    [UIView animateWithDuration:0.25 animations:^{
        CGRect textFrame = ws.inputTextView.frame;
        textFrame.size.height += newHeight - oldHeight;
        ws.inputTextView.frame = textFrame;
        [ws layoutButton:newHeight + 10];
    }];
}

- (void)sendTextWithTextView:(UITextView *)textView {
    if(_delegate && [_delegate respondsToSelector:@selector(inputBar:didSendText:)]) {
        [_delegate inputBar:self didSendText:textView.text];
        [self clearInput];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text
{
    if([text isEqualToString:@"\n"]){
        [self sendTextWithTextView:textView];
        return NO;
    }
    
    if (self.maximumTextLength < NSUIntegerMax) {
        
        // 如果是中文输入法正在输入拼音的过程中（markedTextRange 不为 nil），是不应该限制字数的（例如输入“huang”这5个字符，其实只是为了输入“黄”这一个字符），所以在 shouldChange 这里不会限制，而是放在 didChange 那里限制。
        if (textView.markedTextRange) {
            return YES;
        }
        
        BOOL isDeleting = range.length > 0 && text.length <= 0;
        if (isDeleting) {
            if (NSMaxRange(range) > textView.text.length) {
                // https://github.com/Tencent/QMUI_iOS/issues/377
                return NO;
            } else {
                return YES;
            }
        }
        
        NSUInteger rangeLength =  range.length;
        BOOL textWillOutofMaximumTextLength = textView.text.length - rangeLength + text.length > self.maximumTextLength;
        if (textWillOutofMaximumTextLength) {
            // 当输入的文本达到最大长度限制后，此时继续点击 return 按钮（相当于尝试插入“\n”），就会认为总文字长度已经超过最大长度限制，所以此次 return 按钮的点击被拦截，外界无法感知到有这个 return 事件发生，所以这里为这种情况做了特殊保护
            if (textView.text.length - rangeLength == self.maximumTextLength && [text isEqualToString:@"\n"]) {
                return NO;
            }
            // 将要插入的文字裁剪成多长，就可以让它插入了
            NSInteger substringLength = self.maximumTextLength - textView.text.length + rangeLength;
            
            if (substringLength > 0 && text.length > substringLength) {
                NSString *allowedText = [text qmui_substringAvoidBreakingUpCharacterSequencesWithRange:NSMakeRange(0, substringLength) lessValue:YES countingNonASCIICharacterAsTwo:NO];
                if (allowedText.length <= substringLength) {
                    textView.text = [textView.text stringByReplacingCharactersInRange:range withString:allowedText];
                    textView.selectedRange = NSMakeRange(range.location + substringLength, 0);
                    
                    if ([textView.delegate respondsToSelector:@selector(textViewDidChange:)]) {
                        [textView.delegate textViewDidChange:textView];
                    }
                }
            }
            return NO;
        }
    }
    
    return YES;
}

- (void)onDeleteBackward:(HJResponderTextView *)textView
{
    if (self.delegate && [self.delegate respondsToSelector:@selector(inputBarDidDeleteBackward:)]) {
        [self.delegate inputBarDidDeleteBackward:self];
    }
}

- (void)clearInput
{
    [_inputTextView.textStorage deleteCharactersInRange:NSMakeRange(0, _inputTextView.textStorage.length)];
    [self textViewDidChange:_inputTextView];
}

- (NSString *)getInput
{
    return [_inputTextView.textStorage getPlainString];
}


- (void)addEmoji:(NSString *)emoji
{
    
    [_inputTextView setText:[_inputTextView.text stringByAppendingString:emoji]];
    if (!_inputTextView.markedTextRange) {
        if (_inputTextView.text.length > self.maximumTextLength) {
            _inputTextView.text = [_inputTextView.text qmui_substringAvoidBreakingUpCharacterSequencesWithRange:NSMakeRange(0, self.maximumTextLength) lessValue:YES countingNonASCIICharacterAsTwo:NO];
            return;
        }
    }
    
    if(_inputTextView.contentSize.height > TTextView_TextView_Height_Max){
        float offset = _inputTextView.contentSize.height - _inputTextView.frame.size.height;
        [_inputTextView scrollRectToVisible:CGRectMake(0, offset, _inputTextView.frame.size.width, _inputTextView.frame.size.height) animated:YES];
    }
    
    
    [self textViewDidChange:_inputTextView];
}


- (void)resetTextStyle {
    //After changing text selection, should reset style.
    NSRange wholeRange = NSMakeRange(0, _inputTextView.textStorage.length);
    
    [_inputTextView.textStorage removeAttribute:NSFontAttributeName range:wholeRange];
    [_inputTextView.textStorage removeAttribute:NSForegroundColorAttributeName range:wholeRange];
}

- (void)backDelete {
    [self.inputTextView deleteBackward];
    [self textViewDidChange:_inputTextView];
}

- (void)updateTextViewFrame {
    [self textViewDidChange:[UITextView new]];
}


@end
